/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Deque<TreeNode> stack;
    TreeNode cur = null;
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        stack = new ArrayDeque<TreeNode>();
        pfc(root,p);
        if(stack.peek() == p) {
            cur = null;
        }
        return cur;
    }

    public void pfc(TreeNode root, TreeNode p) {
        if(root == null) {
            return;
        }
        
        pfc(root.left,p);
        if(!stack.isEmpty() && stack.peek() == p) {
            cur = root;
        }
        stack.push(root);
        pfc(root.right,p);
    }
}